import { useState, useCallback, useEffect } from 'react';
import {
  Card,
  Button,
  Input,
  Drawer,
  Form,
  message,
  Space,
  Typography,
  Row,
  Col,
  Tag,
  Select,
  Popconfirm,
  Divider,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import 'github-markdown-css/github-markdown.css';
import MonacoEditor from '@/components/MonacoEditor/MonacoEditor';
import { addArticle, deleteArticle, editArticle, getArticleList } from '@/api/article';
import styles from './index.module.less';
const { Title, Text } = Typography;
const { Option } = Select;

const Article = () => {
  const [form] = Form.useForm();
  const [articles, setArticles] = useState<Article[]>([]);
  const [searchText, setSearchText] = useState('');
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingArticle, setEditingArticle] = useState<Article | null>(null);
  const [previewContent, setPreviewContent] = useState('');

  // 获取文章列表
  const getArticleListHandler = async () => {
    const res = await getArticleList({
      page: 1,
      limit: 100,
    });
    setArticles(res.data.list);
  };

  // 获取文章列表
  useEffect(() => {
    getArticleListHandler();
  }, []);

  // 处理搜索
  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
  }, []);

  // 显示编辑抽屉
  const showDrawer = (article?: Article) => {
    if (article) {
      setEditingArticle(article);
      form.setFieldsValue(article);
      setPreviewContent(article.content);
    } else {
      setEditingArticle(null);
      form.resetFields();
      setPreviewContent('');
    }
    setDrawerVisible(true);
  };

  // 处理添加
  const handleAdd = (
    values: Omit<Article, 'id' | 'created_time' | 'manager_id' | 'manager_name'>
  ) => {
    const newArticle: Omit<Article, 'id' | 'created_time'> = {
      manager_id: 1,
      manager_name: 'admin',
      ...values,
      tags: (values.tags as any).split(','),
    };
    addArticle(newArticle).then((res) => {
      if (res.code === 200) {
        message.success('创建成功');
        getArticleListHandler();
      } else {
        message.error(res.message);
      }
    });
  };

  // 处理编辑
  const handleEdit = (values: Omit<Article, 'created_time' | 'id'>) => {
    if (!editingArticle) return;
    console.log(values);

    editArticle({
      ...values,
      id: editingArticle.id,
      tags: Array.isArray(values.tags) ? values.tags : (values.tags as any).split(','),
      manager_id: 1,
      manager_name: 'admin',
    }).then((res) => {
      if (res.code === 200) {
        message.success('更新成功');
        getArticleListHandler();
      } else {
        message.error(res.message);
      }
    });
  };

  // 处理删除
  const handleDelete = (id: number) => {
    deleteArticle(id.toString()).then((res) => {
      if (res.code === 200) {
        message.success('删除成功');
        getArticleListHandler();
      } else {
        message.error(res.message);
      }
    });
  };

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields().then((values) => {
      if (editingArticle) {
        handleEdit(values);
      } else {
        handleAdd(values);
      }
      setDrawerVisible(false);
      form.resetFields();
    });
  };

  // 处理内容变化
  const handleContentChange = (value: string | undefined) => {
    setPreviewContent(value || '');
    form.setFieldValue('content', value);
  };

  const filteredArticles = articles.filter(
    (article) =>
      article.title.toLowerCase().includes(searchText.toLowerCase()) ||
      article.content.toLowerCase().includes(searchText.toLowerCase())
  );

  return (
    <div className="p-6">
      <Card>
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center">
            <FileTextOutlined className="text-2xl text-blue-600 mr-3" />
            <Title
              level={2}
              className="!mb-0"
            >
              文章管理
            </Title>
          </div>
          <Space size="large">
            <Input.Search
              placeholder="搜索文章标题或内容"
              prefix={<SearchOutlined className="text-gray-400" />}
              value={searchText}
              onChange={(e) => handleSearch(e.target.value)}
              allowClear
              className="w-64"
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => showDrawer()}
              className="bg-blue-600 hover:bg-blue-700"
            >
              新增文章
            </Button>
          </Space>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredArticles.map((article) => (
            <Card
              key={article.id}
              hoverable
              className="overflow-hidden"
            >
              <div className="mb-4">
                <div className="flex justify-between items-start">
                  <Title
                    level={4}
                    className="!mb-2 flex-1"
                  >
                    {article.title}
                  </Title>
                  <Space>
                    <Tag
                      color={
                        article.category === 'poisonous'
                          ? 'red'
                          : article.category === 'medicinal'
                          ? 'blue'
                          : 'green'
                      }
                    >
                      {article.category === 'poisonous'
                        ? '有毒'
                        : article.category === 'medicinal'
                        ? '药用'
                        : '食用'}
                    </Tag>
                  </Space>
                </div>
                <div className="text-gray-500 text-sm mb-2">
                  <Space>
                    <span>作者：{article.manager_name}</span>
                    <Divider type="vertical" />
                    <span>{new Date(article.created_time).toLocaleDateString()}</span>
                  </Space>
                </div>
                <div className={`h-24 overflow-hidden text-gray-600 text-sm`}>
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    rehypePlugins={[rehypeRaw]}
                  >
                    {article.content}
                  </ReactMarkdown>
                </div>
              </div>
              <div className="flex justify-end space-x-2">
                <Button
                  type="text"
                  icon={<EditOutlined />}
                  onClick={() => showDrawer(article)}
                >
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这篇文章吗？"
                  onConfirm={() => handleDelete(article.id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                  >
                    删除
                  </Button>
                </Popconfirm>
              </div>
            </Card>
          ))}
        </div>
      </Card>

      <Drawer
        title={editingArticle ? '编辑文章' : '新增文章'}
        width="80%"
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        extra={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>取消</Button>
            <Button
              type="primary"
              onClick={handleSubmit}
            >
              保存
            </Button>
          </Space>
        }
      >
        <div className="h-full flex flex-col">
          <Form
            form={form}
            layout="vertical"
            className="flex-grow"
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="title"
                  label="文章标题"
                  rules={[{ required: true, message: '请输入文章标题' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="category"
                  label="文章分类"
                  rules={[{ required: true, message: '请选择文章分类' }]}
                >
                  <Select>
                    <Option value="edible">食用</Option>
                    <Option value="poisonous">有毒</Option>
                    <Option value="medicinal">药用</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="tags"
              label="文章标签"
              rules={[{ required: true, message: '请输入文章标签' }]}
            >
              <Input placeholder='请用英文逗号分隔，如: "标签1,标签2"' />
            </Form.Item>

            <Form.Item
              name="color"
              label="颜色"
              rules={[{ required: true, message: '请输入颜色' }]}
            >
              <Input />
            </Form.Item>

            <div className="flex-grow h-[300px] grid grid-cols-2 gap-4">
              <div className="h-full">
                <Form.Item
                  name="content"
                  label="文章内容"
                  className="h-full"
                  rules={[{ required: true, message: '请输入文章内容' }]}
                >
                  <MonacoEditor
                    value={previewContent}
                    onChange={handleContentChange}
                  />
                </Form.Item>
              </div>
              <div className="h-full">
                <Text strong>预览</Text>
                <div
                  className={`${styles.markdown} !mt-3 p-4 overflow-auto border border-gray-200 rounded-md markdown-body !bg-white !text-black`}
                >
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    rehypePlugins={[rehypeRaw]}
                  >
                    {previewContent}
                  </ReactMarkdown>
                </div>
              </div>
            </div>
          </Form>
        </div>
      </Drawer>
    </div>
  );
};

export default Article;
